/**
 * 
 */
package com.webbuilder.utils;

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.util.Date;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.webbuilder.common.Var;


/**
 * @author xcy
 * @created 2016-4-5
 */
public class ReadExcelUtil {

	public static String readXls(String EXCEL_PATH) throws Exception {
		System.out.println("进入readXls方法");
		System.out.println("EXCEL_PATH："+EXCEL_PATH);
		InputStream is = new FileInputStream(EXCEL_PATH);
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
		String strExcel="";
		// 循环工作表Sheet
//		for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
			int numSheet = 0;
			HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
//			if (hssfSheet == null) {
//				continue;
//			}
			// 循环行Row
			for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
				HSSFRow hssfRow = hssfSheet.getRow(rowNum);
				if(null == hssfRow || "".equals(hssfRow)) {
					continue;
				}
		        int cellStart = hssfRow.getFirstCellNum();
		        int cellEnd = hssfRow.getLastCellNum();

				if (hssfRow != null) {
					//HSSFCell cell_1 = hssfRow.getCell(0);
					int flag=0;
					for(int k=cellStart;k<=cellEnd;k++)
			        {
						HSSFCell cell = hssfRow.getCell(k);
						if(null==cell || "".equals(getValue(cell))) {
							if(rowNum>=10){
								if(k==cellStart){
									flag=1;
									break;
								}
							}
							continue;
						}
						if(k==cellEnd){
							strExcel+=(getValue(cell));
						}else{
							strExcel+=(getValue(cell)+",");
						}
			        }
					if(flag==1)break;
					//System.out.println("flag:"+flag);
					strExcel+="\n";
				}
			}
//		}
		System.out.println("strExcel:"+strExcel);
		System.out.println("结束readXls方法");
		return strExcel;
	}
	
	 @SuppressWarnings({ "static-access" })
	private static String getValue(HSSFCell hssfCell) {
		    if (hssfCell.getCellType() == HSSFCell.CELL_TYPE_BLANK){
		    	// 返回空值
		    	return "";
		    } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
	        	// 返回布尔类型的值
	        	return String.valueOf(hssfCell.getBooleanCellValue());
	        } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
	        	// 返回数值类型的值
	        	return String.valueOf(hssfCell.getNumericCellValue());
	        } else {
	        	// 返回字符串类型的值
	        	return String.valueOf(hssfCell.getStringCellValue());
	        }
	    }
}
